package com.orange.common.binding

import android.widget.ImageView
import androidx.databinding.BindingAdapter
import androidx.lifecycle.findViewTreeLifecycleOwner
import coil.load
import com.blankj.utilcode.util.LogUtils

/**
 * Created by Orange on 2022/12/6 21:44.
 */
object ImageViewAdapter {

    @JvmStatic
    @BindingAdapter("android:src")
    fun src(imageView: ImageView, resId: Int) {
        imageView.setImageResource(resId)
    }

    @JvmStatic
    @BindingAdapter(value = ["imageUrl", "placeHolder", "error"], requireAll = false)
    fun load(imageView: ImageView, url: String?,placeHolder: Int = 0, error: Int = 0) {
        loadData(imageView, url,placeHolder,error)
    }

    private fun loadData(imageView: ImageView, data: Any?, placeHolder: Int = 0, error: Int = 0) {
        imageView.load(data) {
            //淡入淡出 开启后会导致 CircleImageView 无法加载 https://github.com/coil-kt/coil/issues/230
            crossfade(false)
            //绑定生命周期
            lifecycle(imageView.findViewTreeLifecycleOwner())
            // allowHardware(false) //如需获取bitmap 需禁止
            if (placeHolder != 0) {
                placeholder(placeHolder) //加载前占位图
            }
            if (error != 0) {
                error(error)       //失败时的错误占位图片
            }
            listener(
//                onStart = {
//                    LogUtils.e("onStart: ")
//                },
//                onCancel = {
//                    LogUtils.e("onCancel: ")
//                },
//                onSuccess = { _,result ->
//                    LogUtils.e("onSuccess: $result")
//                },
                onError = { request, result ->
                    LogUtils.e("onError: $result")
                }
            )
        }
    }
}